package com.erp.erp_ui.Dictionary;

import com.erp.erp_entitys.Dictionary.DictionaryEntity;
import com.erp.erp_entitys.Dictionary.DictionaryEntityExample;
import com.erp.erp_entitys.Dictionary.DictionaryVoEntity;
import com.erp.erp_entitys.Role.RoleEntity;
import com.erp.erp_entitys.RoleGroupMember.RoleGroupMemberEntity;
import com.erp.erp_entitys.User.UserEntity;
import com.erp.erp_servers.Dictionary.IDictionary2Service;
import com.erp.erp_servers.Role.IRoleService;
import com.erp.erp_servers.RoleGroupMember.IRoleGroupMemberService;
import com.erp.erp_servers.User.IUserService;
import com.erp.erp_ui.base.Base;
import com.erp.utils.R;
import com.erp.utils.ResultStatusEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * @ClassName DictionaryKeyControl
 * @Description 字典类
 * @Author songjizhen
 * @Date 2020-06-22 11:38
 * @Version 1.0
 */
@Controller
@RequestMapping(value = "dictionary2")
public class Dictionary2Control  extends Base {
    @Autowired
    IDictionary2Service dictionary2Service;
    @Autowired
    IUserService userService;
    @Autowired
    IRoleService roleService;

    @Autowired
    IRoleGroupMemberService roleGroupMemberService;
    /**
     * 根据字典分类项与分类小项查询出字典列表,此服务为字典获取通过服务，其他服务为字典维护服务
     * @param type
     * @param lx
     * @return
     */
    @RequestMapping(value = "getValue")
    @ResponseBody
    public R<List<DictionaryEntity>> getValue(Integer type, Integer lx ) {

        try{
            List<DictionaryEntity> value= dictionary2Service.getValue(type, lx);
            return R.build(value);
        }
        catch (Exception e){
            e.printStackTrace();
            return R.buildError(ResultStatusEnum.ERROR);
        }
    }
    @RequestMapping(value = "getValueByPage")
    @ResponseBody
    public R<List<DictionaryEntity>> getValueByPage( Integer type, Integer lx,String name ) {//Integer type, Integer lx

        try{

            List<DictionaryEntity> value= dictionary2Service.getValue(type, lx);
            R<List<DictionaryEntity>> build = R.build(value);
            Long count = build.getCount();
            Long total = build.getTotal();
            Integer code = build.getCode();
            Integer status = build.getStatus();
            String msg = build.getMsg();
            List<DictionaryEntity> list=new ArrayList<DictionaryEntity>();
            for(int i=0;i<value.size();i++){
                DictionaryEntity de = value.get(i);
                if(de.getCode() !=null){
                    list.add(de);
                }
            }
            if(name !=null){
                name=name.replace("\"","");
                for(DictionaryEntity de:list){
                    String lxname=de.getLxName();
                    String lname=de.getName();
                    if(lxname ==null){
                        lxname="";
                    }
                    if(lname==null){
                        lname="";
                    }
                     if(lname.indexOf(name)==-1 && lxname.indexOf(name) ==-1){
                         list.remove(de);
                     }

                }
            }
            R<List<DictionaryEntity>> build1 = R.build(list);
            build1.setCode(code);
            build1.setMsg(msg);
            build1.setStatus(status);
            build1.setCount(count);
            build1.setTotal(total);
            return build1;
        }
        catch (Exception e){
            e.printStackTrace();
            return R.buildError(ResultStatusEnum.ERROR);
        }
    }
    @RequestMapping(value = "getValues")
    @ResponseBody
    public R<List<DictionaryEntity>> getValues( Integer type, Integer lx,String name ) {//Integer type, Integer lx

        try{

            List<DictionaryEntity> value= dictionary2Service.getValue(type, lx);
            List<DictionaryEntity> list=new ArrayList<DictionaryEntity>();
            for(int i=0;i<value.size();i++){
                DictionaryEntity de = value.get(i);
                if(de.getCode() !=null){
                    list.add(de);
                }
            }
            if(name !=null){
                name=name.replace("\"","");
                for(DictionaryEntity de:list){
                    String lxname=de.getLxName();
                    String lname=de.getName();
                    if(lxname ==null){
                        lxname="";
                    }
                    if(lname==null){
                        lname="";
                    }
                    if(lname.indexOf(name)==-1 && lxname.indexOf(name) ==-1){
                        list.remove(de);
                    }

                }
            }

            return R.build(list);
        }
        catch (Exception e){
            e.printStackTrace();
            return R.buildError(ResultStatusEnum.ERROR);
        }
    }
    /**
     * 获取所有字典分类列表
     * @return
     */
    @RequestMapping(value = "queryAlllx")
    @ResponseBody
    public R<List<DictionaryVoEntity>> queryAlllx(String name){
        try{
            UserEntity user =(UserEntity) this.getBean("user");
            //字典树
            List<DictionaryVoEntity> values= dictionary2Service.queryAlllx();
            //////////////////////////////////////////////////////
            //获取用户权限
            String[] role=user.getRoles().split(",");
            //获限所有角色列表
            List<String> list2=new ArrayList<>();

            //获取所有角色
            RoleEntity re=new RoleEntity();
            List<RoleEntity> roleEntities = roleService.selectByExample(re);
            Map<String,Object> map=new HashMap<String, Object>();
            for(int i=0;i<roleEntities.size();i++){
                map.put(roleEntities.get(i).getCode(),roleEntities.get(i).getName());
                if(user.getRoles().contains(roleEntities.get(i).getCode())){
                    list2.add(roleEntities.get(i).getCode());
                }
            }
            //获取角色组成员列表 
            RoleGroupMemberEntity record2=new RoleGroupMemberEntity();
            List<RoleGroupMemberEntity> roleGroupMemberEntities = roleGroupMemberService.selectByExample(record2);
            for(RoleGroupMemberEntity rme:roleGroupMemberEntities){
                if(user.getRoles().contains(rme.getGroupCode())){
                    list2.add(rme.getRoleCode());
                }
            }
            //map中去掉没有的权限
            Map<String,Object>mp=new HashMap<>();
            for(Map.Entry<String,Object>entry:map.entrySet()){
                String key=entry.getKey();
                for(int i=0;i<list2.size();i++){
                    if(key.equals(list2.get(i))){
                        String[] num = entry.getValue().toString().split("_");
                        if(num.length == 3){
                            mp.put(num[1],key);
                            break;
                        }

                    }
                }

            }
            //过滤字典树
           // List<DictionaryVoEntity>
            for(int i=0;i<values.size();i++){
                DictionaryVoEntity dve=values.get(i);
                boolean tf=true;
                List<DictionaryVoEntity> li=new ArrayList<>();
                //遍历子节点
                List<DictionaryVoEntity> children = dve.getChildren();
                for(int n=0;n<children.size();n++){
                    DictionaryVoEntity dv=children.get(n);
                     String ZDname=dv.getName();
                     if(mp.get(ZDname) !=null){
                         li.add(dv);
                         tf=false;
                     }
                }
                dve.setChildren(li);
            }
            
/////////////////////////////////////////////////////////////////////////////

            return R.build(values);
        }
        catch (Exception e){
            e.printStackTrace();
            return R.buildError(ResultStatusEnum.ERROR);
        }
    }

    /**
     * 根据主键删除
     * @param ids
     * @return
     */
    @RequestMapping(value = "deleteByPrimaryKey")
    @ResponseBody
    public R<Integer> deleteByPrimaryKey(String[] ids){
        try {
            Integer id=0;
            List<Integer> list=new ArrayList<Integer>();
            for(int i=0;i<ids.length;i++){
                list.add(Integer.parseInt(ids[i].replace("[","").replace("]","")));
                id=Integer.parseInt(ids[i].replace("[","").replace("]",""));
            }
            DictionaryEntityExample example=new DictionaryEntityExample();
            DictionaryEntityExample.Criteria criteria = example.createCriteria();

            DictionaryEntity dictionaryEntity = dictionary2Service.selectByPrimaryKey(id);
            int num=0;
            if(dictionaryEntity.getLx()==24){
                criteria.andTypeEqualTo(Integer.parseInt(dictionaryEntity.getCode()));
                num= dictionary2Service.deleteByExample(example);
                num= dictionary2Service.deleteByPrimaryKey(id);
            }else if(dictionaryEntity.getLx()==25){
                criteria.andLxEqualTo(Integer.parseInt(dictionaryEntity.getCode()));
                num= dictionary2Service.deleteByExample(example);
                num= dictionary2Service.deleteByPrimaryKey(id);
            }else{
                criteria.andIdIn(list);
                num = dictionary2Service.deleteByExample(example);
            }
            return R.build(num);
        }catch (Exception e){
            e.printStackTrace();
            return R.buildError(ResultStatusEnum.ERROR);
        }
    }
private List<RoleEntity> getRole(){
    UserEntity user =(UserEntity) this.getBean("user");
    List<RoleEntity> allRoleByUserCode = userService.getAllRoleByUserCode(user);
        return allRoleByUserCode;
}
    /**
     * 新增或修改
     * @param record
     * @return
     */
    @RequestMapping(value = "insertandupdate",method = RequestMethod.POST)
    @ResponseBody
    public  R<Integer> insertandupdate(@RequestBody DictionaryEntity record){
        try {
             //int insertSelective(DictionaryEntity record);
            int num=0;
            if(record.getId() ==null){
                if(record.getLx()==24){
                    long getcount = this.getcount(record.getLx());
                    record.setCode(getcount+"");
                }else if(record.getLx()==25){
                    long getcount = this.getcount(record.getLx());
                    record.setCode(getcount+"");
                }
                if(this.is_exits(record.getType(),record.getLx(),record.getCode())){
                    record.setCode(System.currentTimeMillis()+"");
                }
                num = dictionary2Service.insertSelective(record);
                if(record.getLx()==24){
                    DictionaryEntity re=new DictionaryEntity();
                    re.setType(Integer.parseInt(record.getCode()));
                    dictionary2Service.insertSelective(re);
                }
                if(record.getLx()==25){
                    DictionaryEntity re=new DictionaryEntity();
                    re.setType(Integer.parseInt(record.getDj()+""));
                    re.setLx(Integer.parseInt(record.getCode()+""));
                    re.setRemark("views/jsp/SystemCenter/tpl/customersource.jsp");
                    dictionary2Service.insertSelective(re);
                }
            }else {
                num = dictionary2Service.updateByPrimaryKeySelective(record);
            }
            return  R.build(num);
        }catch (Exception e){
            e.printStackTrace();
            return R.buildError(ResultStatusEnum.ERROR);
        }
    }
    private long getcount(Integer ty){
        long cun=0;
        DictionaryEntityExample example=new DictionaryEntityExample();
        DictionaryEntityExample.Criteria criteria = example.createCriteria();
        criteria.andTypeEqualTo(6);
        if(ty==24){
            criteria.andLxEqualTo(24);
            cun = dictionary2Service.countByExample(example)+1;
        }
        if(ty==25){
            criteria.andLxEqualTo(25);
            cun = dictionary2Service.countByExample(example)+1;
        }
        return cun;
    }
    private Boolean is_exits(Integer dl,Integer xl,String code){
        DictionaryEntityExample example=new DictionaryEntityExample();
        DictionaryEntityExample.Criteria criteria = example.createCriteria();
        criteria.andTypeEqualTo(dl);
        criteria.andLxEqualTo(xl);
        criteria.andCodeEqualTo(code);
        long l = dictionary2Service.countByExample(example);
        return  l==1?true:false;
    }
}
